package org.jeecg.modules.xxgx.djgl.dto;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xxgx.djgl.vo.Ret;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class BaseValid<T> {
    public Ret<String> validate(T t) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(t);
        if (CollectionUtil.isNotEmpty(violations)) {
            List<String> errorList= violations.stream().map(ConstraintViolation<T>::getMessageTemplate).collect(Collectors.toList());
            String errorStr =  StringUtils.join(errorList.toArray(), ",");
            return Ret.fail(errorStr);
        }
        return Ret.success();
    }
}
